<script setup lang="ts">
import { request } from '@/api';
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant';
import { onMounted, ref } from 'vue';
import base64ToBlob from 'b64-to-blob'

// 是否显示 拍照、相册交互弹框
const showAvatarSheet = ref(false)

const actions = [
  { name: '拍照' },
  { name: '相册' }
]

const onCancel = () => {
  showToast('取消')
}

const onSelect = async (action: ActionSheetAction, index: number) => {
  // 存放图片的base64，假设目前通过方法获取的图片是jpeg格式
  let res = ''
  if (index === 0) {
    res = await mk.pickerCamera()
  } else if (index === 1) {
    res = await mk.pickerPhoto()
  }
  profile.value.avatar = 'data:image/jpeg;base64,'+ res
}

// 用户信息
const profile = ref<ProfileInfo>({} as ProfileInfo)

// 生日选择弹框相关
const showBirthdayPop = ref(false)
const currentDate = ref(['2000', '11', '13'])
const minDate = new Date(1970, 1, 1)
const maxDate = new Date(2026, 1, 1)
const onBirthdayConfirm = () => {
  profile.value.birthday = currentDate.value.join('-')
  showBirthdayPop.value = false
}
// 地区选择弹框相关
const showAreaPop = ref(false)
const areaList = ref<AreaColumns>({} as AreaColumns)
const onAreaConfirm = ({ selectedValues, selectedOptions, selectedIndexes }) => {
  // console.log(selectedValues)
  // console.log(selectedOptions)
  // console.log(selectedIndexes)
  profile.value.provinceCode = selectedValues[0]
  profile.value.cityCode = selectedValues[1]
  profile.value.countryCode = selectedValues[2]
  const arr = selectedOptions.map(v => {
    return v.text
  })
  profile.value.fullLocation = arr.join(' ')
  showAreaPop.value = false
}
// 职业选择弹框相关
const showJobPop = ref(false)
const selectedJob = ref<string[]>([])
const jobList = [
  { text: '程序员', value: 'IT' },
  { text: '医生', value: 'Doctor' },
  { text: '厨师', value: 'Chef' },
  { text: '主播', value: 'Anchor' },
  { text: '教师', value: 'Teacher' },
]
const onJobConfirm = ({ selectedValues }) => {
  // console.log(`当前值: ${selectedValues.join('')}`);
  profile.value.profession = selectedValues.join('')
  showJobPop.value = false
}

onMounted(async () => {
  const geoInfo = await mk.getAreaColumns()
  areaList.value = geoInfo
  showLoadingToast({ message: '加载中...', duration: 0, forbidClick: true})
  const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
  closeToast()
  profile.value = res.data.result
  currentDate.value = profile.value.birthday.split('-')
  selectedJob.value = [profile.value.profession]
})

const onSubmit = async () => {
  // 判断是否更新了头像，更新了才需要上传头像
  if(profile.value.avatar.startsWith('data:image/jpeg;base64')) {
    // 执行上传头像过程
    try {
      const image = base64ToBlob(profile.value.avatar.slice(23), 'image/jpeg')
      const fd = new FormData()
      // 这个 'file' 需要和接口文档中定义的参数名一致
      fd.append('file', image, Date.now() + '.jpeg')
      const res = await request.post<MkResponse<{ avatar: string }>>('member/profile/avatar', fd)
      const user = mk.queryUser()
      user.avatar = res.data.result.avatar
      mk.updateUser(user)
    } catch (err) {
      showToast({ message: '上传头像失败' })
    }
  }
  // 提交其他数据
  const res = await request.put<MkResponse<ProfileInfo>>('/member/profile', profile.value)
  // console.log(res)
  mk.updateUser(res.data.result)
  showToast('更新成功')
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true">
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>

    <!-- 底部拍照、相册交互弹框 -->
    <van-action-sheet
      v-model:show="showAvatarSheet"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @cancel="onCancel"
      @select="onSelect"
    />

    <!-- 生日选择弹框 -->
    <van-popup
     v-model:show="showBirthdayPop"
     position="bottom"
     ><van-date-picker
        v-model="currentDate"
        title="选择日期"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onBirthdayConfirm"
        @cancel="showBirthdayPop=false"
    /></van-popup>

    <!-- 地区选择弹框 -->
    <van-popup
     v-model:show="showAreaPop"
     position="bottom"
     ><van-area
        title="选择省市区"
        :area-list="areaList"
        @confirm="onAreaConfirm"
        @cancel="showAreaPop=false"
    /></van-popup>

    <!-- 职业选择弹框 -->
     <van-popup
     v-model:show="showJobPop"
     position="bottom"
     ><van-picker
        title="选择职业"
        :columns="jobList"
        v-model="selectedJob"
        @confirm="onJobConfirm"
        @cancel="showJobPop=false"
    /></van-popup>

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field v-model="profile.account" label="账号" readonly></van-field>
      <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field v-model="profile.birthday" @click="showBirthdayPop=true" label="生日" readonly placeholder="请选择日期"></van-field>
      <van-field v-model="profile.fullLocation" @click="showAreaPop=true" label="所在地" readonly placeholder="请选择所在地"></van-field>
      <van-field v-model="profile.profession" @click="showJobPop=true" label="职业" readonly placeholder="请选择职业"></van-field>
    </van-cell-group>

    <div class="submit">
      <van-button @click="onSubmit" round block type="primary">
        保存资料
      </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>